package com.liming.cartype.webapp.wicket.page;

import com.liming.cartype.api.biz.IParameterItemService;
import com.liming.cartype.api.biz.IParameterService;
import com.liming.cartype.api.persistence.impl.ParameterBeanImpl;
import com.liming.cartype.api.persistence.impl.ParameterItemBeanImpl;
import org.apache.aries.blueprint.annotation.Reference;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormValidatingBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.util.time.Duration;

import javax.inject.Inject;
import javax.inject.Named;

/**
 * Created by Administrator on 14-5-5.
 */
public class AddParameterItemForm extends Panel {
    @Named
    @Inject
    @Reference(id = "parameterItemService", serviceInterface = IParameterItemService.class)
    private IParameterItemService parameterItemService;
    public AddParameterItemForm(String id, final ParameterBeanImpl parameterBean){
        super(id);

        final Form<ParameterItemBeanImpl> form = new Form<ParameterItemBeanImpl>("add_carType_form", new CompoundPropertyModel<ParameterItemBeanImpl>(new ParameterItemBeanImpl()));
        add(form);
        AjaxFormValidatingBehavior.addToAllFormComponents(form, "keydown", Duration.ONE_SECOND);

        TextField formName = new TextField("name");

        form.add(formName);

        form.add(new AjaxButton("submit_button", form){
            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> submitForm) {
                ParameterItemBeanImpl parameterItemBean = form.getModelObject();
                parameterItemBean.setParameterId(parameterBean.getId());
                parameterItemService.putParameterItem(parameterItemBean);
                target.appendJavaScript("$('#form_modal2').css({'display':'none'});" +
                        "$('div.modal-backdrop.fade.in').removeClass().addClass('div.modal-backdrop.fade.out')");
            }

            @Override
            protected void onError(AjaxRequestTarget target, Form<?> form) {
                System.out.println("onError");
            }
        });

        add(new Link("reset_from_1") {
            @Override
            public void onClick() {
                form.setModelObject(new ParameterItemBeanImpl());
            }
        });

        form.add(new Link("reset_from_2") {
            @Override
            public void onClick() {
                form.setModelObject(new ParameterItemBeanImpl());
            }
        });
    }
}
